<template>
  <div style="width: 80%; margin: 40px auto">
    <!-- 搜索区域 -->
    <div class="filter-container" style="margin-bottom: 10px; float: left">
      <el-input 
        placeholder="工号/姓名搜索" 
        v-model="queryString" 
        style="width: 200px;" 
        class="filter-item"
        @keyup.enter="fetchData"
      />
      <el-button @click="fetchData">查询</el-button>
    </div>

    <!-- 新增按钮 -->
    <el-row class="mb-4" style="float: right">
      <el-button type="primary" @click="setState('add', null)">新增</el-button>
    </el-row>
<!-- 2.讲解 -->
    <!-- 用户表格 -->
    <el-table 
      :data="pagedDataList" 
      style="width: 100%" 
      stripe 
      highlight-current-row
    >
      <el-table-column prop="id" label="工号" align="center" />
      <el-table-column prop="name" label="姓名" align="center" />
      <el-table-column prop="sex" label="性别" align="center" />
      <el-table-column prop="phone" label="电话" align="center" />
      <el-table-column prop="idcard" label="班级" align="center" />
      <el-table-column prop="workaddress" label="权限" align="center" />
      <el-table-column prop="entrydate" label="时间" align="center" />
      <el-table-column fixed="right" label="Operations" width="180px">
        <template #default="scope">
          <el-button 
            size="small" 
            @click="setState('update', scope.row)"
          >
            编辑
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px; float: right"
    ></el-pagination>

    <!-- 编辑/新增弹窗 -->
    <el-dialog
      v-model="centerDialogVisible"
      :title="state === 'add' ? '添加用户' : '编辑用户'"
      width="40%"
      align-center
    >
      <span>
        <el-form :model="form" label-width="120px">
          <el-form-item label="工号">
            <el-input 
              :disabled="state === 'update'" 
              v-model="form.id" 
              placeholder="请输入工号" 
            />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="form.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="性别">
            <el-input v-model="form.sex" placeholder="请输入性别" />
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="form.phone" placeholder="请输入电话号" />
          </el-form-item>
          <el-form-item label="班级">
            <el-input v-model="form.idcard" placeholder="请输入班级" />
          </el-form-item>
          <el-form-item label="权限">
            <el-input v-model="form.workaddress" placeholder="请输入权限" />
          </el-form-item>
          <el-form-item label="时间">
            <el-input v-model="form.entrydate" type="date" />
          </el-form-item>
        </el-form>
      </span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit(state)">
            {{ state === "add" ? "添加" : "编辑" }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import Mock from 'mockjs';

// 模拟用户数据（持久化存储）
const mockUsers = ref([]);
// 初始化 Mock 数据（若为空则生成）
if (!localStorage.getItem('mockUsers')) {
  const initialData = Mock.mock({
    'data|30': [
      {
        'id|+1': 1000,
        name: '@cname',
        sex: '@pick(["男", "女"])',
        phone: /^1[3-9]\d{9}$/,
        idcard: '@id',
        workaddress: '@pick(["管理员", "普通用户"])',
        entrydate: '@date("yyyy-MM-dd")'
      }
    ]
  }).data;
  localStorage.setItem('mockUsers', JSON.stringify(initialData));
  mockUsers.value = initialData;
} else {
  mockUsers.value = JSON.parse(localStorage.getItem('mockUsers'));
}

// 响应式数据
const queryString = ref('');     // 搜索关键字
const currentPage = ref(1);      // 当前页码
const pageSize = ref(10);        // 每页条数
const total = ref(0);            // 总条数
const pagedDataList = ref([]);   // 分页后的数据
const centerDialogVisible = ref(false); // 弹窗显隐
const form = reactive({          // 弹窗表单数据
  id: "",
  name: "",
  sex: "",
  phone: "",
  idcard: "",
  workaddress: "",
  entrydate: ""
});
const state = ref("add");        // 弹窗状态（add/update）

// 初始化数据
onMounted(() => {
  fetchData();
});

// 获取数据（含搜索、分页）
const fetchData = () => {
  // 1. 搜索过滤
  const filtered = mockUsers.value.filter(item => 
    item.id.toString().includes(queryString.value) || 
    item.name.includes(queryString.value)
  );

  // 2. 分页处理
  total.value = filtered.length;
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  pagedDataList.value = filtered.slice(start, end);
};
// 7.讲解
// 监听搜索关键字变化
watch(queryString, () => {
  currentPage.value = 1; // 搜索后重置页码
  fetchData();
});

// 弹窗状态控制
const setState = (type, row) => {
  centerDialogVisible.value = true;
  state.value = type;
  if (type === 'update') {
    // 编辑时赋值
    form.id = row.id;
    form.name = row.name;
    form.sex = row.sex;
    form.phone = row.phone;
    form.idcard = row.idcard;
    form.workaddress = row.workaddress;
    form.entrydate = row.entrydate;
  } else {
    // 新增时清空表单
    form.id = '';
    form.name = '';
    form.sex = '';
    form.phone = '';
    form.idcard = '';
    form.workaddress = '';
    form.entrydate = '';
  }
};

// 提交（新增/编辑）
const submit = (type) => {
  if (type === "add") {
    // 新增：生成唯一 ID（Mock 方式）
    const newId = Mock.Random.integer(1000, 9999);
    form.id = newId;
    mockUsers.value.push({ ...form });
  } else if (type === "update") {
    // 编辑：找到对应用户并更新
    const index = mockUsers.value.findIndex(item => item.id === form.id);
    if (index !== -1) {
      mockUsers.value[index] = { ...form };
    }
  }
  // 持久化到 localStorage
  localStorage.setItem('mockUsers', JSON.stringify(mockUsers.value));
  // 关闭弹窗 + 刷新数据
  centerDialogVisible.value = false;
  fetchData();
};

// 删除用户
const handleDelete = (id) => {
  // 过滤掉被删除的用户
  mockUsers.value = mockUsers.value.filter(item => item.id !== id);
  // 持久化 + 刷新数据
  localStorage.setItem('mockUsers', JSON.stringify(mockUsers.value));
  fetchData();
};

// 分页 - 每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchData();
};

// 分页 - 当前页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};
</script>

<style scoped>
.filter-container {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>